﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace LoadTestDbToXml
{
    class ApplicationRunner
    {
        public static void Run(string connectionString, string xmlFileName)
        {
            using (var dataAccessService = new DataAccessService(connectionString))
            {
                LoadTestRun lastTestRun = dataAccessService.GetLastTestRun();
                int loadTestRunId = lastTestRun.LoadTestRunId;
                var prevTransactions = dataAccessService.GetPrevTransactions(
                    loadTestRunId);

                var loadTestRuns = dataAccessService.LoadTestRuns;

                var xmlGenerator = new XmlGenerator(lastTestRun, prevTransactions, loadTestRuns);

                var loadTestTestResults =
                    dataAccessService.GetResults(loadTestRunId);

                var errorMessages =
                    dataAccessService.GetErrorMessages(loadTestRunId);

                var transactions =
                    dataAccessService.GetTransactions(loadTestRunId);

                var counterSamples = dataAccessService.GetCounters(loadTestRunId);

                foreach (var testResult in loadTestTestResults)
                {
                    xmlGenerator.AddResult(testResult);
                }

                foreach (var transaction in transactions)
                {
                    xmlGenerator.AddTransaction(transaction, prevTransactions);
                }

                foreach (var messageSummary in errorMessages)
                {
                    xmlGenerator.AddException(messageSummary);
                }

                List<CounterGroup> counterGroups = CountersReader.Read("Counters.xml");
                foreach (var counterGroup in counterGroups)
                {
                    xmlGenerator.AddCounterGroup(counterGroup, counterSamples);
                }

                xmlGenerator.Save(xmlFileName);
            }

        }
    }
}
